package com.lyn.anr.handler

import com.lyn.anr.entity.InvokeInfo
import com.lyn.anr.interfaces.InvokeListener
import com.lyn.anr.pool.InvokeInfoPool
import java.util.concurrent.ArrayBlockingQueue

/**
 * Anr 处理
 * @author longyn 2025/07/15
 * @version 1.0.0
 */
internal object AnrHandler {


    private val invokeInfoArrayBlockingQueue: ArrayBlockingQueue<InvokeInfo> =
        ArrayBlockingQueue(1024)
    var invokeListener: InvokeListener? = null

    var threshold = 0L


    init {
        Thread {
            while (true) {
                try {
                    val take = invokeInfoArrayBlockingQueue.take()
                    val id = take.id
                    val className = take.className
                    val methodName = take.methodName
                    val timeMillis = take.timeMillis
                    val threadName = take.threadName
                    if (timeMillis >= threshold) {
                        invokeListener?.onInvoke(id, className, methodName, timeMillis, threadName)
                    }
                    InvokeInfoPool.recycling(take)
                } catch (_: Throwable) {

                }
            }
        }.start()
    }

    fun push(info: InvokeInfo) {
        try {
            invokeInfoArrayBlockingQueue.add(info)
        } catch (_: Throwable) {
        }
    }

}